package com.mall.shopping.services;

import com.mall.shopping.MyCartServcie;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.CartProductDto;
import com.mall.shopping.dto.DeleteCartItemResponse;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

@Service
@Component
public class MyCartServcieImpl implements MyCartServcie {

    @Autowired
    RedissonClient redissonClient;

    @Override
    public DeleteCartItemResponse delectSimple(Integer userId) {

        RMap<Long, CartProductDto> map = redissonClient.getMap(userId.toString());
        Set<Map.Entry<Long, CartProductDto>> entries = map.entrySet();

        for (Map.Entry<Long, CartProductDto> entry : entries) {
            CartProductDto cartProductDto = entry.getValue();
            String checked = cartProductDto.getChecked();
            if ("true".equals(checked)){
                map.fastRemove(entry.getKey());
            }
        }
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        return deleteCartItemResponse;
    }

    @Override
    public DeleteCartItemResponse checkedAll(Map map) {

        Object checked = map.get("checked");
        Object userId = map.get("userId");

        RMap<Long, CartProductDto> map1 = redissonClient.getMap(userId.toString());
        Set<Map.Entry<Long, CartProductDto>> entries = map1.entrySet();
        for (Map.Entry<Long, CartProductDto> entry : entries) {
            if (checked.equals("ture")){
                entry.getValue().setChecked("false");
            }else{
                entry.getValue().setChecked("false");
            }
        }

        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
        deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        return deleteCartItemResponse;
    }
}
